

# pip3 install -i https://pypi.doubanio.com/simple paho-mqtt
from paho.mqtt import client as mqtt_client
import time
class TMq :
    def __init__(self):
        self.host = "127.0.0.1"
        self.port = 31274
        self.uid = "admin"
        self.pwd = "hhuc1115"
        self.clientId = ""
        self.client = None
        self.subscribeTopics=[]
        self.actived = False
        self.events ={
            "onConnect": self.eventOnConnect,               #eventOnConnect(client, userdata, flags, rc)
            "onDisConnect": self.eventOnDisconnect,         #eventOnDisConnect(client, userdata, rc)
            "onMessage": self.eventOnMessage,               #eventOnMessage(client, userdata, topic, payload,  message)
        }

    def isConnected(self):
        res = False
        try:
            res = self.client!=None and self.actived
        except Exception as er:
            res = False
            print(er)
        return res
    def connect(self):
        try:
            userData ={"o:""mqc-2024"}
            if self.client ==None:
                self.client =  mqtt_client.Client( client_id=None, clean_session=True, userdata=userData, transport="tcp")
            else:
                self.client.reinitialise(None, clean_session=True , userdata=userData)
            self.client.username_pw_set( username=self.uid , password= self.pwd)
            self.client.on_connect = self.on_connect
            self.client.on_disconnect = self.on_disconnect
            self.client.on_message = self.on_message
            self.client.connect(host=self.host , port=self.port , keepalive=60 )
            self.actived = True
        except Exception as er :
            print(er)
        res = self.isConnected()
        return  res
    def start(self, asyncFlag = False):
        try:
            self.connect()
            time.sleep(1.0)
            flag = self.isConnected()
            if flag:
                if asyncFlag :
                    self.client.loop_start()
                else:
                    self.client.loop_forever()
        except Exception as er :
            print(er)
        res = self.isConnected()
        return  res
    def disConnect(self):
        try:
            pass
        except Exception as er :
            print(er)
    def sendMsg(self, topic , messagePayload):
        try:
            flag = self.isConnected()
            if flag :
                self.client.publish(topic=topic, payload=messagePayload, retain=False)
        except Exception as er :
            print(er)
    def subscribe(self, topics):
        try:
            self.client.subscribe(topics)
        except Exception as er :
            print(er)
    def on_connect(self , client, userdata, flags, rc):
        try:
            print('connect to mqtt broker', "flags=", flags, "rc=", rc)
            if rc==0 :
                self.actived = True
                if len( self.subscribeTopics)>0:
                    self.client.subscribe(self.subscribeTopics)
            else:
                self.actived = False
            if "onConnect" in self.events.keys() and  self.events["onConnect"]!=None:
                fun = self.events["onConnect"]
                fun(client,userdata, flags, rc)
        except Exception as er :
            print(er)
    def on_disconnect(self , client, userdata, rc):
        try:
            print('disconnect from mqtt broker', "rc=", rc)
            self.actived = False
            if "onDisConnect" in self.events.keys() and  self.events["onDisConnect"]!=None:
                fun = self.events["onDisConnect"]
                fun(client,userdata, rc)
        except Exception as er :
            print(er)
    def on_message(self , client, userdata, message):
        try:
            print('rec message from  mqtt broker', message)
            print('topic=', message.topic)
            print('payload=', str(message.payload) )
            if "onMessage" in self.events.keys() and  self.events["onMessage"]!=None:
                fun = self.events["onMessage"]
                fun(client,userdata, message.topic , str(message.payload) , message)
        except Exception as er :
            print(er)
    def eventOnConnect(self , client, userdata, flags, rc):
        try:
            pass
        except Exception as er :
            print(er)
    def eventOnDisconnect(self , client, userdata, rc):
        try:
            pass
        except Exception as er :
            print(er)
    def eventOnMessage(self , client, userdata, topic, payload,  message):
        try:
            pass
        except Exception as er :
            print(er)

mqclient = TMq()
